package com.xiongda.tools;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.xiongda.exception.MyException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分页工具
 *
 * @author 缪琼
 */
public class Page<T> {

    /**
     * 往Map集合中添加页面参数
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Map<String, Object> setPageParams() {
        Map<String, Object> map = new HashMap<>();
        map.put("pageIndex", pageIndex);
        map.put("pageSize", pageSize);
        return map;
    }

    /**
     * 往Map集合中添加页面参数
     *
     * @param map
     * @return
     */
    public Map<String, Object> addPageParams(Map<String, Object> map) {
        map.put("pageIndex", pageIndex);
        map.put("pageSize", pageSize);
        return map;
    }

    public static final int PAGE_SIZE = 10;// 默认页容量为10
    private int pageNo;// 当前页
    private int pageSize;// 页容量
    private int pageIndex;// 第一条数据的索引
    private int total;// 总条数
    private int pageCount;// 总页数
    private List<T> items = new ArrayList<T>();// 数据集合

    public Page(int pageNo, int pageSize) {
        this.pageIndex = (pageNo - 1) * pageSize;
        this.pageNo = pageNo;
        this.pageSize = pageSize;
    }

    public int getPageNo() {
        return pageNo;
    }

    public int getPageSize() {
        return pageSize;
    }

    public int getPageIndex() {
        return pageIndex;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
        try {
            pageCount = total / pageSize;
            if (total % pageSize > 0)
                pageCount++;
        } catch (MyException e) {
            pageCount = 0;
            throw new MyException("页容量参数错误");
        }
    }

    public int getPageCount() {
        return pageCount;
    }

    public List<T> getItems() {
        return items;
    }

    public void setItems(List<T> items) {
        this.items = items;
    }

    @JsonIgnore
    public boolean isHasNext() {
        return pageNo + 1 <= getPageCount();
    }

    @JsonIgnore
    public int getNextPage() {
        if (isHasNext())
            return pageNo + 1;
        return this.pageNo;
    }

    @JsonIgnore
    public boolean isHasPre() {
        return pageNo - 1 >= 1;
    }

    @JsonIgnore
    public int getPrePage() {
        if (isHasPre())
            return pageNo - 1;
        return pageNo;
    }
}
